import puppeteer from "puppeteer";
//调用python脚本
import { spawn } from "child_process";
// 接受参数
const key = process.argv[2];
console.log("process.argv: ", process.argv);
//每个操作都是异步的 需要加await
/**
 * 1.创建一个浏览器对象
 * headless:false 默认无头模式 关闭无头模式 这样就可以看到浏览器在干嘛
 */
const browser = await puppeteer.launch({ headless: false });
//2.搞个页面
const page = await browser.newPage();
//3.跳转页面
await page.setViewport({ width: 1280, height: 768 });
await page.goto("https://www.juejin.cn");
//4.为了代码健壮 等待元素出现再操作
await page.waitForSelector(".side-navigator-wrap");
const collectFn = async () => {
  await page.waitForSelector(".entry-list");
  const titles = [];
  const elements = await page.$$(".entry-list .title-row .title");
  for await (const el of elements) {
    const prop = await el.getProperty("innerText");
    const text = await prop.jsonValue();
    titles.push(text);
  }
  const pyProcess = spawn("python3", ["index.py", titles.join(",")]);
  pyProcess.stdout.on("data", (data) => {
    console.log("data: ", data.toString());
  });
  pyProcess.stderr.on("data", (data) => {
    console.log("data: ", data.toString());
  });
  pyProcess.on("close", (code) => {
    console.log("code: ", code);
  });
  console.log("titles: ", titles);
};
//5.$获取单个元素 $$获取多个元素
const elements = await page.$$(".side-navigator-wrap .nav-item-wrap span");
for await (const el of elements) {
  const prop = await el.getProperty("innerText");
  const text = await prop.jsonValue();
  console.log("text: ", text, key);
  if (text === (key || "前端")) {
    await el.click();
    collectFn();
    break;
  }
}
